package com.zone.vehicle.superApps.view.login.message;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.module.account.entity.CaptchaGetEntity;
import com.zone.sdk.module.account.entity.CheckCaptchaEntity;
import com.zone.sdk.module.account.entity.LoginEntity;
import com.zone.sdk.module.account.entity.UserInfoEntity;
import com.zone.vehicle.lib.view.captcha.model.CaptchaGetIt;
import com.zone.vehicle.lib.view.captcha.widget.BlockPuzzleDialog;
import com.zone.vehicle.lib.view.captcha.widget.DragImageView;
import com.zone.vehicle.superApps.R;
import com.zone.vehicle.superApps.databinding.FragmentLoginMessageBinding;
import com.zone.vehicle.superApps.model.LoggedInUserView;
import com.zone.vehicle.superApps.model.LoginViewModel;
import com.zone.vehicle.superApps.model.ViewModelFactory;
import com.zone.vehicle.superApps.utils.PhoneUtils;
import com.zone.vehicle.superApps.view.common.HandledFragment;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import static com.zone.vehicle.superApps.view.login.LoginFragment.LOGIN_SECRET_FRAGMENT;
import static com.zone.vehicle.superApps.view.login.LoginFragment.SET_SECRET_FRAGMENT;

public class LoginMessageFragment extends HandledFragment {

    private static final String TAG = LoginMessageFragment.class.getSimpleName();

    private LoginViewModel viewModel;
    private FragmentLoginMessageBinding binding;

//    private CaptchaDialog captchaDialog;
    private BlockPuzzleDialog blockPuzzleDialog;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FragmentLoginMessageBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(this, new ViewModelFactory())
                .get(LoginViewModel.class);
        initView();
        initListener();
    }
    
    private void initView(){
//        captchaDialog = new CaptchaDialog(this.requireContext());
        blockPuzzleDialog = new BlockPuzzleDialog(this.requireContext());
    }

    private void initListener(){

        binding.btnCode.setOnClickListener(v -> {
            if (checkPhone(binding.phone.getText().toString())){
                binding.loading.setVisibility(View.VISIBLE);
                viewModel.captchaGet();
                viewModel.getPhone().setValue(binding.phone.getText().toString());
            }
        });

        blockPuzzleDialog.setDragListenner(new DragImageView.DragListenner() {
            @Override
            public void onDrag(double position) {
                CaptchaGetEntity entity = viewModel.getCaptchaGet().getValue();
                if (ObjectUtils.isNotEmpty(entity)){
                    viewModel.checkCaptcha(position, entity.getToken(), entity.getSecretKey());
                }
            }
        });

        viewModel.getCaptchaGet().observe(getViewLifecycleOwner(), new Observer<CaptchaGetEntity>() {
            @Override
            public void onChanged(CaptchaGetEntity captchaGetEntity) {
                if (ObjectUtils.isNotEmpty(captchaGetEntity)){
                    binding.loading.setVisibility(View.GONE);
                    CaptchaGetIt data = new CaptchaGetIt();
                    data.setJigsawImageBase64(captchaGetEntity.getJigsawImageBase64());
                    data.setOriginalImageBase64(captchaGetEntity.getOriginalImageBase64());
                    data.setSecretKey(captchaGetEntity.getSecretKey());
                    data.setToken(captchaGetEntity.getToken());
//                BeanUtils.copyProperties(captchaGetEntity, data);
                    blockPuzzleDialog.setData(data);
                    blockPuzzleDialog.show();
                }
            }
        });
        viewModel.getCheckCaptcha().observe(getViewLifecycleOwner(), new Observer<CheckCaptchaEntity>() {
            @Override
            public void onChanged(CheckCaptchaEntity checkCaptchaEntity) {
                if (ObjectUtils.isEmpty(checkCaptchaEntity)){
                    viewModel.captchaGet();
                }
            }
        });
        viewModel.getCaptcha_certificate().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (StringUtils.isNotEmpty(s)){
                    blockPuzzleDialog.ok();
                    blockPuzzleDialog.cancel();
                    viewModel.loginPhoneCode(requireContext(), binding.phone.getText().toString(), s);
                }else {
                    viewModel.captchaGet();
                }
            }
        });

        binding.btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBack();
            }
        });

        binding.secret.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePage(LOGIN_SECRET_FRAGMENT);
            }
        });

        binding.btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = binding.phone.getText().toString();
                String code = binding.code.getText().toString();
                if (checkPhone(phone) && checkCode(code)){
                    viewModel.loginPhoneCodeCheck(phone, code);
                }
            }
        });

        viewModel.getLoginEntity().observe(getViewLifecycleOwner(), new Observer<LoginEntity>() {
            @Override
            public void onChanged(LoginEntity loginEntity) {
                if (ObjectUtils.isNotEmpty(loginEntity) && loginEntity.getFirst_login()==2){
                    changePage(SET_SECRET_FRAGMENT);
                }else {
                    viewModel.queryUserInfo(requireContext());
                }
            }
        });

        viewModel.getUserInfo().observe(getViewLifecycleOwner(), new Observer<UserInfoEntity>() {
            @Override
            public void onChanged(UserInfoEntity userInfoEntity) {
                // TODO 此处应该判断查询用户信息正确性
                requireActivity().finish();
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
//                viewModel.loginDataChanged(binding.phone.getText().toString(),
//                        binding.code.getText().toString());
            }
        };
        binding.phone.addTextChangedListener(afterTextChangedListener);
        binding.code.addTextChangedListener(afterTextChangedListener);
//        binding.code.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_DONE) {
//                    viewModel.login(binding.phone.getText().toString(),
//                            binding.code.getText().toString());
//                }
//                return false;
//            }
//        });

//        binding.btnFinish.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                binding.loading.setVisibility(View.VISIBLE);
//                viewModel.login(binding.phone.getText().toString(),
//                        binding.code.getText().toString());
//            }
//        });

        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                blockPuzzleDialog.fail(result.getResultMsg());
                showLoginFailed(result.getResultMsg());
            }
        });
    }

    private boolean checkPhone(String phone){
        if (!PhoneUtils.isPhoneNum(phone)){
            Toast.makeText(
                    requireContext(),
                    "请输入手机号码",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    private boolean checkCode(String code){
        if (!StringUtils.isNotEmpty(code)){
            Toast.makeText(
                    requireContext(),
                    "请输入验证码",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        // TODO : initiate successful logged in experience
        if (getContext() != null && getContext().getApplicationContext() != null) {
            // TODO 如果用户首次登录（未设置密码）
            changePage(SET_SECRET_FRAGMENT);
//            Toast.makeText(getContext().getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
        }
    }

    private void showLoginFailed(String errorString) {
        binding.loading.setVisibility(View.GONE);
        if (getContext() != null && getContext().getApplicationContext() != null) {
            Toast.makeText(
                    getContext().getApplicationContext(),
                    errorString,
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void finish(){
        getActivity().finish();
    }

}